package com.xmutca.micro.uaa.service;


import com.xmutca.micro.uaa.model.User;
import com.xmutca.micro.uaa.repository.UserRepository;
import com.xmutca.micro.uaa.security.UserAuthDetails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

  @Autowired
  private UserRepository userRepository;

  @Override
  public UserDetails loadUserByUsername(String username) {
    User user = this.userRepository.findByUsername(username);

    if (user == null) {
      throw new UsernameNotFoundException(String.format("No user found with username '%s'.", username));
    } else {
      return create(user);
    }
  }

  public UserAuthDetails create(User user) {
    Collection<SimpleGrantedAuthority> authorities = new ArrayList<>();
    if (user.getUsername().equals("admin")) {
      authorities.add(new SimpleGrantedAuthority("ADMIN"));
    }
    authorities.add(new SimpleGrantedAuthority("USER"));
    return new UserAuthDetails(user.getId(), user.getUsername(), user.getPassword(), authorities);
  }
}
